import Vue from 'vue'

//仅支持大小写字母,数字和汉字
Vue.directive('filterSpecialChar', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            let newinput = undefined
            if (_input.className.indexOf('el-input') > -1) {
                newinput = _input.getElementsByTagName('input')[0]
            } else {
                newinput = _input
            }
            if (!newinput.value) { //此处需获取input标签
                return false;
            }
            newinput.value = newinput.value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, "");
            newinput.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//仅支持大小写字母和汉字
Vue.directive('supportLetterChinese', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            let maxLength = undefined
            if (value != undefined) {
                if (value.maxLen > 0) {
                    maxLength = value.maxLen
                }
            }
            let newinput = undefined
            if (_input.className.indexOf('el-input') > -1) {
                newinput = _input.getElementsByTagName('input')[0]
            } else {
                newinput = _input
            }
            if (!newinput.value) { //此处需获取input标签
                return false;
            }
            newinput.value = newinput.value.replace(/[^\a-\z\A-\Z\u4E00-\u9FA5]/g, "");
            if (maxLength != undefined) {
                newinput.value = newinput.value.substring(0, maxLength)
            }
            newinput.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//仅支持大小写字母,数字
Vue.directive('filterLetterNumber', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            let maxLength = undefined
            if (value != undefined) {
                if (value.maxLen > 0) {
                    maxLength = value.maxLen
                }
            }
            let newinput = undefined
            if (_input.className.indexOf('el-input') > -1) {
                newinput = _input.getElementsByTagName('input')[0]
            } else {
                newinput = _input
            }
            if (!newinput.value) { //此处需获取input标签
                return false;
            }
            newinput.value = newinput.value.replace(/[^\a-\z\A-\Z0-9]/g, "");
            if (maxLength != undefined) {
                newinput.value = newinput.value.substring(0, maxLength)
            }
            newinput.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//仅支持小数
//integerDigits参数无最大值限制,默认4
//decimal参数最大值为1默认2 
//eg: v-filterDecimal="{'integer':4,'decimal':3}"
Vue.directive('filterDecimal', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            let integerDigits = 4
            let decimalDigits = 2

            if (value != undefined) {
                integerDigits = value.integer != undefined ? value.integer : 4
                decimalDigits = value.decimal != undefined ? value.decimal : 2
            }
            let newinput = undefined
            if (_input.className.indexOf('el-input') > -1) {
                newinput = _input.getElementsByTagName('input')[0]
            } else {
                newinput = _input
            }
            if (!newinput.value) { //此处需获取input标签
                return false;
            }
            //禁止录入整数部分两位以上，但首位为0
            newinput.value = newinput.value.replace(/^([1-9]\d*(\.[\d]{0,10})?|0(\.[\d]{0,10})?)[\d.]*/g, '$1');
            //禁止录入整数部分超过6位
            newinput.value = newinput.value.replace(eval("/^([1-9]\\d{" + (integerDigits - 1) + "})\\d*/g"), '$1');
            //替换除了数字和.以外的字符
            newinput.value = newinput.value.replace(/[^\d\.]/g, '');
            //第一个输入.  则自动变为0.
            newinput.value = newinput.value.replace(/^\./g, '0.');
            //保证.只出现一次，而不能出现两次以上 2..    2.2.2
            newinput.value = newinput.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            //只能输入两个小数
            newinput.value = newinput.value.replace(eval("/^(\\-)*(\\d+)\\.(\\d{" + decimalDigits + "}).*$/"), '$1$2.$3');
            newinput.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) {
            console.log(e)
        }
    }
})

//仅支持数字 input type字段使用text
Vue.directive('supportNumber', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            if (!_input.value) { //此处需获取input标签
                return false;
            }
            _input.value = _input.value.replace(/[^0-9]/g, "");
            _input.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//仅支持数字 input type字段使用text
Vue.directive('filterNumber', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            let newinput = undefined
            if (_input.className.indexOf('el-input') > -1) {
                newinput = _input.getElementsByTagName('input')[0]
            } else {
                newinput = _input
            }
            if (!newinput.value) { //此处需获取input标签
                return false;
            }
            console.log(newinput.value)
            newinput.value = newinput.value.replace(eval(/[^0-9]{2}/g), "");
            newinput.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//仅支持数字和小数 input type字段使用text
Vue.directive('filterAmountOfMoney', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            if (!_input.value) { //此处需获取input标签
                return false;
            }
            //禁止录入整数部分两位以上，但首位为0
            _input.value = _input.value.replace(/^([1-9]\d*(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, '$1');
            //禁止录入整数部分超过6位
            _input.value = _input.value.replace(/^([1-9]\d{5})\d*/g, '$1');
            //替换除了数字和.以外的字符
            _input.value = _input.value.replace(/[^\d\.]/g, '');
            //第一个输入.  则自动变为0.
            _input.value = _input.value.replace(/^\./g, '0.');
            //保证.只出现一次，而不能出现两次以上 2..    2.2.2
            _input.value = _input.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            //只能输入两个小数
            _input.value = _input.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            _input.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) {
            console.log(e)
        }
    }
})
//仅支持数字和小数 input type字段使用text
Vue.directive('filterAmountOfMoneys', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            if (!_input.value) { //此处需获取input标签
                return false;
            }
            //禁止录入整数部分两位以上，但首位为0
            _input.value = _input.value.replace(/^([1-9]\d*(\.[\d]{0,2})?|0(\.[\d]{0,2})?)[\d.]*/g, '$1');
            //禁止录入整数部分超过6位
            _input.value = _input.value.replace(/^([1-9]\d{2})\d*/g, '$1');
            //替换除了数字和.以外的字符
            _input.value = _input.value.replace(/[^\d\.]/g, '');
            //第一个输入.  则自动变为0.
            _input.value = _input.value.replace(/^\./g, '0.');
            //保证.只出现一次，而不能出现两次以上 2..    2.2.2
            _input.value = _input.value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
            //只能输入两个小数
            _input.value = _input.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
            _input.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) {
            console.log(e)
        }
    }
})


//屏蔽空格
Vue.directive('preventSpace', {
    update: function (_input, {
        value,
        modifiers
    }, vnode) {
        try {
            if (!_input.value) { //此处需获取input标签
                return false;
            }
            _input.value = _input.value.replace(" ", "");
            _input.dispatchEvent(new Event(modifiers.lazy ? 'change' : 'input'))
        } catch (e) { }
    }
})

//禁止按钮重复点击
Vue.directive('preventReClick', {
    inserted(el, binding) {
        el.addEventListener('click', () => {
            if (!el.disabled) {
                el.disabled = true
                setTimeout(() => {
                    el.disabled = false
                }, binding.value || 2000)
            }
        })
    }
})


//改变node状态
Vue.directive('changeState', {
    update: function (el, binding, vnode) {
        let cels = el.getElementsByTagName('input')
        for (let i in cels) {
            let cel = cels[i]
            console.log('-', cel)
            try {
                if (binding.value) {
                    cel.setAttribute('disabled', 'disabled')
                } else {
                    cel.removeAttribute('disabled')
                }
            } catch (e) {
                //TODO handle the exception
            }
        }
        if (binding.value) {
            el.setAttribute('disabled', 'disabled')
        } else {
            el.removeAttribute('disabled')
        }
    }
})

// 点击水波纹
Vue.directive("waves", {
    // 当被绑定的元素插入到 DOM 中时触发
    inserted: (el, binding) => {
      // 给当前el添加v-waves类
      addClass(el, "v-waves");
  
      // 绑定参数
      const params = binding.value || {};
  
      // 持续时间
      const duration = params.duration || 750;
  
      // 展示水波纹函数
      function show(event) {
        const pDiv = event.target,
          cDiv = document.createElement("div");
        pDiv.appendChild(cDiv);
        const rectObj = forRect(pDiv),
          _height = event.pageY - rectObj.top,
          _left = event.pageX - rectObj.left,
          _scale = "scale(" + (pDiv.clientWidth / 100) * 10 + ")";
        const position = {
          top: _height + "px",
          left: _left + "px"
        };
        (cDiv.className = cDiv.className + " v-waves-animation"),
          cDiv.setAttribute("style", forStyle(position)),
          (position["-webkit-transform"] = _scale),
          (position["-moz-transform"] = _scale),
          (position["-ms-transform"] = _scale),
          (position["-o-transform"] = _scale),
          (position.transform = _scale),
          (position.opacity = "1"),
          (position["-webkit-transition-duration"] = duration + "ms"),
          (position["-moz-transition-duration"] = duration + "ms"),
          (position["-o-transition-duration"] = duration + "ms"),
          (position["transition-duration"] = duration + "ms"),
          (position["-webkit-transition-timing-function"] =
            "cubic-bezier(0.250, 0.460, 0.450, 0.940)"),
          (position["-moz-transition-timing-function"] =
            "cubic-bezier(0.250, 0.460, 0.450, 0.940)"),
          (position["-o-transition-timing-function"] =
            "cubic-bezier(0.250, 0.460, 0.450, 0.940)"),
          (position["transition-timing-function"] =
            "cubic-bezier(0.250, 0.460, 0.450, 0.940)"),
          cDiv.setAttribute("style", forStyle(position));
        const finishStyle = {
          opacity: 0,
          "-webkit-transition-duration": duration + "ms",
          "-moz-transition-duration": duration + "ms",
          "-o-transition-duration": duration + "ms",
          "transition-duration": duration + "ms",
          "-webkit-transform": _scale,
          "-moz-transform": _scale,
          "-ms-transform": _scale,
          "-o-transform": _scale,
          top: _height + "px",
          left: _left + "px"
        };
        setTimeout(function() {
          cDiv.setAttribute("style", forStyle(finishStyle));
          setTimeout(function() {
            pDiv.removeChild(cDiv);
          }, duration);
        }, 100);
      }
  
      // 添加点击监听
      el.addEventListener(
        "click",
        e => {
          show(e);
        },
        false
      );
    }
  });
  
  // ------------------以下为工具函数------------------
  // 添加类
  function addClass(el, className) {
    if (!className) return;
  
    const els = Array.isArray(el) ? el : [el];
  
    els.forEach(el => {
      if (el.classList) {
        el.classList.add(className.split(" "));
      } else {
        el.className += ` ${className}`;
      }
    });
  }
  // 样式string拼凑
  function forStyle(position) {
    let cssStr = "";
    for (const key in position) {
      if (position.hasOwnProperty(key)) cssStr += key + ":" + position[key] + ";";
    }
    return cssStr;
  }
  // 获取鼠标点击位置
  function forRect(target) {
    let position = {
        top: 0,
        left: 0
      },
      ele = document.documentElement;
    "undefined" != typeof target.getBoundingClientRect &&
      (position = target.getBoundingClientRect());
    return {
      top: position.top + window.pageYOffset - ele.clientTop,
      left: position.left + window.pageXOffset - ele.clientLeft
    };
  }
